import path from 'node:path';
import { app, ipcMain, BrowserWindow } from 'electron';

const isDevelopment = !app.isPackaged;

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.js
// │
process.env.DIST = path.join(__dirname, '../dist');
process.env.PUBLIC = isDevelopment ? path.join(process.env.DIST, '../public') : process.env.DIST;

let win: BrowserWindow | null;
// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL'];

function createWindow() {
  win = new BrowserWindow({
    icon: path.join(process.env.PUBLIC, 'electron-vite.svg'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  if (isDevelopment) {
    win.webContents.openDevTools();
  }

  // Test active push message to Renderer-process.
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', new Date().toLocaleString());
  });

  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL);
  } else {
    // win.loadFile('dist/index.html')
    win.loadFile(path.join(process.env.DIST, 'index.html'));
  }
}

app.on('window-all-closed', () => {
  win = null;
});

app.whenReady().then(createWindow);

// 接收异步消息
ipcMain.on('asynchronous-message', function (event, msg) {
  console.log('接收的渲染进程异步消息', msg);
  // 回复异步消息
  event.sender.send('asynchronous-reply', '回复渲染进程异步消息');
});
// 接收同步消息
ipcMain.on('synchronous-message', function (event, msg) {
  console.log('接收的渲染进程异步消息', msg);
  event.returnValue = '回复渲染进程同步消息';
});
